package com.homedo.odin.solution.service.bizservice.wap;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.homedo.core.common.base.dto.Meta;
import com.homedo.core.common.exception.BizException;
import com.homedo.core.common.util.BeanUtils;
import com.homedo.core.common.util.ListSortUtil;
import com.homedo.core.common.util.NumberHelper;
import com.homedo.core.common.util.ParamCheckUtil;
import com.homedo.odin.solution.contract.personal.userhomepage.AddPopularityReq;
import com.homedo.odin.solution.contract.wap.SolutionAppDetailResp;
import com.homedo.odin.solution.contract.wap.SolutionAppIndexResp;
import com.homedo.odin.solution.contract.wap.SolutionListResp;
import com.homedo.odin.solution.enumcode.basic.ErrorCodeEnum;
import com.homedo.odin.solution.enumcode.brand.FirmStatusEnum;
import com.homedo.odin.solution.enumcode.other.PopularityEnum;
import com.homedo.odin.solution.enumcode.solution.SolutionStateEnum;
import com.homedo.odin.solution.enumcode.solution.SolutionTypeEnum;
import com.homedo.odin.solution.enumcode.user.RoleEnum;
import com.homedo.odin.solution.model.dto.PdfImagesResponseBean;
import com.homedo.odin.solution.model.dto.SolutionListResponseBean;
import com.homedo.odin.solution.model.entity.BrandFirm;
import com.homedo.odin.solution.model.entity.BrandOwner;
import com.homedo.odin.solution.model.entity.ExpertProfile;
import com.homedo.odin.solution.model.entity.Solution;
import com.homedo.odin.solution.model.entity.UserProfile;
import com.homedo.odin.solution.service.BrandFirmServiceImpl;
import com.homedo.odin.solution.service.BrandOwnerServiceImpl;
import com.homedo.odin.solution.service.ExpertProfileServiceImpl;
import com.homedo.odin.solution.service.SmsServiceImpl;
import com.homedo.odin.solution.service.SolutionServiceImpl;
import com.homedo.odin.solution.service.UserProfileServiceImpl;
import com.homedo.odin.solution.service.bizservice.personal.CommonBizService;
import com.homedo.odin.solution.service.common.HomedoService;
import java.util.List;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.ArrayUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @author: zhaoxudong
 * @date: 2018/3/27 17:36
 * @Description:
 */
@Service
public class WapSolutionsBizService {

    @Autowired
    SolutionServiceImpl solutionService;
    @Autowired
    BrandOwnerServiceImpl brandOwnerService;
    @Autowired
    BrandFirmServiceImpl brandFirmService;
    @Autowired
    HomedoService homedoService;
    @Autowired
    CommonBizService commonBizService;
    @Autowired
    ExpertProfileServiceImpl expertProfileService;
    @Autowired
    UserProfileServiceImpl profileService;
    @Autowired
    SmsServiceImpl smsServiceImpl;

    /**
     * 获取方案列表
     *
     * @param solutionType 方案类型1:系统方案 2:品牌方案
     * @param brandId 品牌id
     * @param sysAttr 系统属性(一级系统属性)
     * @param buildingType 建筑业态
     * @param pageNum 当前页码
     * @param pageSize 每页记录数
     */
    public SolutionListResp querySolutionsByParams(Integer solutionType, Integer brandId, Integer sysAttr,
            Integer buildingType, Integer pageNum, Integer pageSize) {
        ParamCheckUtil.checkPageParam(pageNum, pageSize);
        PageHelper.startPage(pageNum, pageSize);
        if (solutionType != null && solutionType != 1 && solutionType != 2) {
            throw new BizException(Meta.CODE_451.getCode(), "方案类型不合规");
        }
        PageInfo<SolutionListResponseBean> beanPageInfo = new PageInfo<>(solutionService
                .querySolutionsByParams(solutionType, brandId, sysAttr, buildingType,
                        SolutionStateEnum.SHELVE.getDbValue(), null));
        return BeanUtils.transfrom(SolutionListResp.class, beanPageInfo);
    }

    /**
     * 获取方案详情
     */
    public SolutionAppDetailResp solutionDetail(Long solutionId) {
        if (solutionId == null || solutionId < 0) {
            throw new BizException(Meta.CODE_451);
        }
        Solution solution = solutionService.findBySolutionId(solutionId);
        if (solution == null) {
            throw new BizException(ErrorCodeEnum.NotExist.getDbValue(), "该方案不存在！");
        }
        if (SolutionStateEnum.UNSHELVE.getDisplayValue().equals(solution.getStatus())) {
            throw new BizException(ErrorCodeEnum.NotExist.getDbValue(), "该方案已下架！");
        }
        //设置方案基本信息
        SolutionAppDetailResp resp = BeanUtils.transfrom(SolutionAppDetailResp.class, solution);
        resp.setCreateTimeStr(solution.getCreateTime());
        //设置品牌信息
        BrandOwner brandOwner = brandOwnerService.findById(solution.getBrandId());
        if (brandOwner != null) {
            resp.setBrandIcon(brandOwner.getBrandIcon());
            resp.setBrandName(brandOwner.getBrandName());
        }
        //设置品牌厂商信息
        BrandFirm firm = brandFirmService
                .findFirmByUserIdAndStatus(solution.getUserId(), FirmStatusEnum.AUDITPASS.getDbValue());
        if (firm != null) {
            resp.setFirmName(firm.getFirmName());
        }
        //设置专家方案
        resp.setIsExpert(false);
        if (NumberHelper.validatePositive(solution.getUserId())) {
            ExpertProfile expert = expertProfileService.getExpert(solution.getUserId());
            if (expert != null) {
                resp.setIsExpert(true);
            }
        }
        //获取附件内容图片
        String url = null;
        String attachment = solution.getAttachment();
        String[] a = attachment.split("\\|\\|");
        for (int i = 0; i < a.length; i++) {
            String format = a[i].substring(a[i].lastIndexOf(".") + 1);
            if (("pdf").equals(format) || ("pptx").equals(format) || ("ppt").equals(format)) {
                url = a[i];
                break;
            } else if (("docx").equals(format) || ("doc").equals(format)) {
                url = a[i];
                break;
            }
        }
        List<PdfImagesResponseBean> images = homedoService.getPdfToImages(url);
        if (url != null) {
            //对list排序
            ListSortUtil.sort(images, "id", true);
            /*
                页数 > 40 ，显示前35%页，向下取整；
                10 < 页数 <= 40，显示前40%页，向下取整，至少显示5页；
                页数 <=10，显示前5页；
                页数 < 5，后台不会审核通过
            */
            if (images.size() > 30) {
                resp.setImageList(images.subList(0, 30));
            } else {
                resp.setImageList(images);
            }
        } else {
            resp.setImageList(images);
        }
        //浏览数+1
        solutionService.addSolutionPageView(solution.getSolutionId());
        //增加人气
        if (solution.getUserId() != null && solution.getUserId() > 0) {
            AddPopularityReq req = new AddPopularityReq();
            req.setType(PopularityEnum.VisitProduct.getType());
            req.setTargetId(solution.getUserId());
            commonBizService.addPopularity(req);
        }
        //发短信
        smsServiceImpl.sendVisitSolutionSMS(solution);
        return resp;
    }

    public SolutionListResp solutionListForBrandFirm(Integer uid, Integer pageNum, Integer pageSize) {
        ParamCheckUtil.checkUserId(uid);
        ParamCheckUtil.checkPageParam(pageNum, pageSize);
        PageHelper.startPage(pageNum, pageSize);
        UserProfile profile = profileService.selectByUserId(uid);
        if (profile == null || RoleEnum.BRANDOWNER.getDbValue().equals(profile.getRole())) {
            throw new BizException(ErrorCodeEnum.NotExist.getDbValue(), "该用户不是品牌主");
        }
        PageInfo<SolutionListResponseBean> beanPageInfo = new PageInfo<>(
                solutionService.querySolutionsByParams(SolutionTypeEnum.BRAND_SOLUTION.getDbValue(),
                        null, null, null, SolutionStateEnum.SHELVE.getDbValue(), uid));
        SolutionListResp resp = BeanUtils.transfrom(SolutionListResp.class, beanPageInfo);
        return resp;
    }

    /**
     * 获取热榜图片
     */
    public SolutionAppIndexResp hotPics() {
        SolutionAppIndexResp resp = new SolutionAppIndexResp();
        List<SolutionListResponseBean> solutionDayList = solutionService.queryHotSolutionList(1, 1);
        //默认方案
        List<Solution> list = solutionService.querySolutionListForHome(1);
        if (CollectionUtils.isNotEmpty(solutionDayList)) {
            for (SolutionListResponseBean hotSolutionList : solutionDayList) {
                resp.setSolutionDayPic(hotSolutionList.getMatchPic());
            }
        } else {
            for (Solution solution : list) {
                resp.setSolutionDayPic(solution.getMatchPic());
            }
        }
        //周热榜图片
        List<SolutionListResponseBean> solutionWeekList = solutionService.queryHotSolutionList(2, 1);
        if (CollectionUtils.isNotEmpty(solutionWeekList)) {
            for (SolutionListResponseBean hotSolutionList : solutionWeekList) {
                resp.setSolutionWeekPic(hotSolutionList.getMatchPic());
            }
        } else {
            for (Solution solution : list) {
                resp.setSolutionWeekPic(solution.getMatchPic());
            }
        }
        //月热榜图片
        List<SolutionListResponseBean> solutionMonthList = solutionService.queryHotSolutionList(3, 1);
        if (CollectionUtils.isNotEmpty(solutionMonthList)) {
            for (SolutionListResponseBean hotSolutionList : solutionMonthList) {
                resp.setSolutionMonthPic(hotSolutionList.getMatchPic());
            }
        } else {
            for (Solution solution : list) {
                resp.setSolutionMonthPic(solution.getMatchPic());
            }
        }
        return resp;
    }

    /**
     * 获取热榜
     */
    public SolutionListResp hotList(Integer type, Integer number) {
        if (!ArrayUtils.contains(new int[]{1, 2, 3}, type)) {
            throw new BizException(Meta.CODE_451.getCode(), "type类型不正确");
        }
        if (number == null || number <= 0) {
            throw new BizException(Meta.CODE_451.getCode(), "number不合法");
        }
        PageHelper.startPage(1, number);
        PageInfo<SolutionListResponseBean> beanPageInfo = new PageInfo<>(
                solutionService.queryHotSolutionList(type, null));
        return BeanUtils.transfrom(SolutionListResp.class, beanPageInfo);
    }
}
